<?php
/**
 * 自定义日志信息
 */

namespace App\Common\Logs;

use Illuminate\Support\Facades\File;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Logs
{
    // 自定义日期时间格式
    const DATE_FORMAT = 'Y-m-d H:i:s';

    /**
     * 成功信息日志
     * @param $msg //信息提示
     * @param $data //数据
     * @param $outInputType //1=输出json格式的字符串  2=数组格式
     * @param $filename //文件名称
     * @return void
     */
    public static function info($msg, $data = [], $outInputType = 1, $filename = 'laravel')
    {
        //创建文件夹
        $folderPath = storage_path('logs/normal/' . date("ymd"));
        if(!file_exists($folderPath)){
            mkdir($folderPath, 0775, true);
        }
        $filePath = storage_path('logs/normal/' . date("ymd") . "/" . $filename . '.log');
        $log = new Logger('log');
        $handle = new StreamHandler($filePath, Logger::DEBUG,true,0775);
        $handle->setFormatter(new LineFormatter(null, self::DATE_FORMAT, true, true));
        $log->pushHandler($handle);
        if ($outInputType == 1) {//json格式的字符串
            $log->info($msg, $data);
        } else {
            //日志记录 json格式的字符串转数组格式
            $logStr = $msg;
            if($data){
                $logStr.=PHP_EOL;
                foreach ($data as $k => $v) {
                    if (is_array($v)) {
                        $logStr .= "[{$k}] => " . json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . " " . PHP_EOL;
                    } else {
                        $logStr .= "[{$k}] => {$v}" . PHP_EOL;
                    }
                }
                $logStr = rtrim($logStr);
            }
            $log->info($logStr);
        }
    }

    /**
     * 错误信息日志
     * @param $msg //信息提示
     * @param $data //数据
     * @param $outInputType //1=输出json格式的字符串  2=数组格式
     * @param $filename //文件名称
     * @return void
     */
    public static function error($msg, $data = [], $outInputType = 1, $filename = 'error')
    {
        self::info($msg, $data, $outInputType, $filename);
    }

    /**
     * 定时任务信息日志
     * @param $msg  //信息提示
     * @param $data //数据
     * @param $filename //文件名称
     * @return void
     */
    public static function crontabLog($msg,$data=[],$filename='crontab')
    {
        //创建文件夹
        $folderPath = storage_path('logs/crontabs/' . date("ymd"));
        if(!file_exists($folderPath)){
            mkdir($folderPath, 0775, true);
        }
        $filePath = storage_path('logs/crontabs/' . date("ymd") . "/" . $filename . '.log');
        $log = new Logger('log');
        $handle = new StreamHandler($filePath, Logger::DEBUG,true,0775);
        $handle->setFormatter(new LineFormatter(null, self::DATE_FORMAT, true, true));
        $log->pushHandler($handle);
        $log->info($msg,$data);
    }


}
